package com.hry.sunflower.interceptor;

import com.hry.sunflower.common.Constant;
import com.hry.sunflower.pojo.User;
import com.hry.sunflower.util.CookieUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器，拦截未登录用户 控制跳转
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从session中获取用户信息
        User user = (User) request.getSession(true).getAttribute(Constant.CURRENT_USER);
        // 没有登录跳转到登录界面
        if (user == null) {
            String loginBackUrl = request.getRequestURI();
            if (loginBackUrl.equals("")) {
                loginBackUrl = "/page/index";
            }
            CookieUtil.addCookie(Constant.LOGIN_BACK_RUL, loginBackUrl, response);
            response.sendRedirect("/page/login");
            return false;
        }
        return true;
    }
}
